package com.ctl.szmd.szmd.init

import android.app.Application
import android.content.Context
import androidx.startup.Initializer
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.Utils
import com.ctl.lib_common.utils.LocalCache
import com.ctl.lib_common.utils.http.HttpEngine
import com.ctl.szmd.szmd.di.appModules
import com.tencent.smtt.export.external.TbsCoreSettings
import com.tencent.smtt.sdk.QbSdk
import com.tencent.smtt.sdk.TbsListener
import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidFileProperties
import org.koin.android.ext.koin.androidLogger
import org.koin.core.context.startKoin

/**
 * created by : chentl
 * Date: 2020/12/10
 */
class AppInitializer : Initializer<Unit> {

    override fun create(context: Context) {
        Utils.init(context as Application?)
        LocalCache.initialize(context)
        initQbSdk(context)
        HttpEngine.buildRetrofit("http://www.baidu.com")

        startKoin {
            androidLogger()//用来打印日志
            androidContext(context)//向Koin中注入context
            androidFileProperties()//从assets中读取保存的数据
            modules(appModules)//注册声明的Module
        }
    }

    private fun initQbSdk(context: Context) {
        val map = mutableMapOf<String, Any>()
        map[TbsCoreSettings.TBS_SETTINGS_USE_SPEEDY_CLASSLOADER] = true
        map[TbsCoreSettings.TBS_SETTINGS_USE_DEXLOADER_SERVICE] = true
        QbSdk.initTbsSettings(map)

        QbSdk.setDownloadWithoutWifi(true)
        QbSdk.setTbsListener(object : TbsListener {
            override fun onDownloadFinish(i: Int) {
                LogUtils.i("app", "onDownloadFinish -->下载X5内核完成：$i")
            }

            override fun onInstallFinish(i: Int) {
                LogUtils.i("app", "onInstallFinish -->安装X5内核进度：$i")
            }

            override fun onDownloadProgress(i: Int) {
                LogUtils.i("app", "onDownloadProgress -->下载X5内核进度：$i")
            }
        })

        val cb: QbSdk.PreInitCallback = object : QbSdk.PreInitCallback {
            override fun onViewInitFinished(arg0: Boolean) {
                //x5內核初始化完成的回调，true表x5内核加载成功，否则表加载失败，会自动切换到系统内核。
                LogUtils.i("app", " 内核加载 $arg0")
            }

            override fun onCoreInitFinished() {}
        }

        //x5内核初始化接口
        QbSdk.initX5Environment(context, cb)
    }

    override fun dependencies(): MutableList<Class<out Initializer<*>>> = mutableListOf()
}